package com.n9.qq.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * zip压缩解压缩工具
 * @author ice
 * @since 2019/2/22 16:00
 */
public class ZipUtils {
    /**
     * 解压缩数据
     * @param zipData
     * @return
     */
    public static byte[] inflate(byte[] zipData) {
        Inflater inflater = new Inflater();
        inflater.setInput(zipData);
        ByteArrayOutputStream aos = new ByteArrayOutputStream();

        try {
            byte[] temp = new byte[1024];
            int len;
            while(!inflater.finished()) {
                len = inflater.inflate(temp);
                if (len > 0) {
                    aos.write(temp, 0, len);
                }
            }
            return aos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            inflater.end();
            try {
                aos.close();
            } catch (IOException e) {
                //ignore
            }
        }
    }

    /**
     * 压缩数据
     * @param srcData
     * @return
     */
    public static byte[] deflate(byte[]  srcData) {
        ByteArrayOutputStream aos=new ByteArrayOutputStream();
        Deflater inflater=new Deflater();
        try {
            inflater.setInput(srcData);
            inflater.finish();
            byte[] buff=new byte[1024];
            int byteNum;
            while(!inflater.finished()){
                byteNum=inflater.deflate(buff);
                aos.write(buff, 0, byteNum);
            }
            return aos.toByteArray();
        } finally {
            inflater.end();
        }
    }

}
